package fr.kotton.myorganizer.utils.sql;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import fr.kotton.myorganizer.db.MyOrganizerDbHelper;
import fr.kotton.myorganizer.task.interfaces.TaskGroupsQueryCompleteListener;
import fr.kotton.myorganizer.task.interfaces.TasksQueryCompleteListener;

public class DatabaseReader extends AsyncTask<SqlQuery, Void, Cursor> {

    private MyOrganizerDbHelper mDbHelper;
    private TasksQueryCompleteListener mTasksCallback;
    private TaskGroupsQueryCompleteListener mGroupsCallback;

    public DatabaseReader(Context pContext, TasksQueryCompleteListener SqlQueryCompleteListener) {
        super();
        mDbHelper = new MyOrganizerDbHelper(pContext);
        mTasksCallback = SqlQueryCompleteListener;
    }

    public DatabaseReader(Context pContext, TaskGroupsQueryCompleteListener SqlQueryCompleteListener) {
        super();
        mDbHelper = new MyOrganizerDbHelper(pContext);
        mGroupsCallback = SqlQueryCompleteListener;
    }

    @Override
    protected Cursor doInBackground(SqlQuery... pSqlReadQueries) {

        SQLiteDatabase lDatabase = mDbHelper.getReadableDatabase();

        Cursor lCursor = null;

        if (pSqlReadQueries[0] instanceof SqlReadQuery) {

            SqlReadQuery lSqlReadQuery = (SqlReadQuery) pSqlReadQueries[0];

            lCursor = lDatabase.query(
                    lSqlReadQuery.getTable(),                    // The table to query
                    lSqlReadQuery.getColumns(),                               // The columns to return
                    lSqlReadQuery.getSelection(),                                // The columns for the WHERE clause
                    lSqlReadQuery.getSelectionArgs(),                            // The values for the WHERE clause
                    lSqlReadQuery.getGroupBy(),                                     // don't group the rows
                    lSqlReadQuery.getHaving(),                                     // don't filter by row groups
                    lSqlReadQuery.getOrderBy(),                                // The sort order
                    lSqlReadQuery.getLimit()
            );

        } else if (pSqlReadQueries[0] instanceof SqlRawQuery) {

            SqlRawQuery lSqlRawQuery = (SqlRawQuery) pSqlReadQueries[0];

            lCursor = lDatabase.rawQuery(lSqlRawQuery.getQuery(), null);
        }

        return lCursor;
    }

    @Override
    protected void onPostExecute(Cursor pCursor) {

        if (mTasksCallback != null) {
            mTasksCallback.onTasksReadQueryComplete(pCursor);
        } else if (mGroupsCallback != null) {
            mGroupsCallback.onTaskGroupsReadQueryComplete(pCursor);
        }
    }
}